package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: javase
 * @description: 使用Lock锁ReentrantLock
 * @author: lld
 * @create: 2021-03-21 20:49
 **/
public class ReentrantLockTest {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station, "x").start();
        new Thread(station, "y").start();
        new Thread(station, "z").start();
    }
}

class BuyTicket implements Runnable {
    private int num = 100;
    private boolean flag = true;

    //可重入锁,没有参数默认为非公平锁，可以设置为true
    private final ReentrantLock lock = new ReentrantLock();

    //使用解决
    public void buy() throws InterruptedException {

        try {
            lock.lock();//加锁
            if (num <= 0) {
                flag = false;
                return;
            }
            //模拟延迟
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName() + " buy " + num--);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
